import Vue from 'vue';
import { parseToObject } from '@/utils';
import { INITIAL_FORM_QUERY_VALUE, STATUS_TYPES, HANDLE_TYPE } from '../../constants';
import { ChannelTree } from '@/components';
import { loadAuditTaskBoard } from './api';
import { message } from '@/utils/util';

Vue.component(ChannelTree.name);

export default {
  name: 'audit-price-header-form',
  components: { ChannelTree },
  props: {
    // 顶级渠道列表
    topChannelList: {
      type: Array,
      default: () => [],
    },
    // 总的蜂窝列表
    cellularList: {
      type: Array,
      default: () => [],
    },
    // 表单默认值
    defaultFormQueryValueStr: String,
    // 查询状态
    querying: {
      type: Boolean,
      default: false,
    },
  },

  data() {
    return {
      formQuery: { ...INITIAL_FORM_QUERY_VALUE },
      labelWidth: '100px',
      statusTypes: STATUS_TYPES,
      auditTime: [],
      channels: [],
      cellulars: [],
      handleTypes: HANDLE_TYPE,
      auditTaskBoard: {},
    };
  },
  watch: {
    // 监听传入的表单默认值变化--特殊场景如跳到当前页面携带查询参条件
    defaultFormQueryValueStr(newValue) {
      if (!newValue) {
        return;
      }
      this.formQuery = {
        ...this.formQuery,
        ...parseToObject(newValue),
      };
    },
  },
  methods: {
    onQuery() {
      this.$emit('onQuery', { ...this.formQuery });
      this.getAuditTaskBoard();
    },
    reset() {
      this.formQuery = { ...INITIAL_FORM_QUERY_VALUE };
      this.channels = [];
      this.cellulars = [];
      this.auditTime = [];
    },
    // 创建时间 change
    timeChange(time) {
      if (time) {
        this.formQuery = { ...this.formQuery, timeRange: { startTime: this.auditTime[0], endTime: this.auditTime[1] } };
      } else {
        this.auditTime = [];
        this.formQuery = { ...this.formQuery, timeRange: null };
      }
    },
    // 选择渠道编码
    affirmChannel(channels) {
      this.channels = channels;
      this.formQuery.channelCodes = this.channels.map(item => item.id);
      this.checkedSize = channels.length;
      console.log(this.formQuery);
    },
    // 顶级渠道 change 触发：更新蜂窝列表
    topChannelChange(code) {
      this.cellulars = [];
      if (code) {
        this.cellularList.forEach(item => {
          if (item.topChannelCode === code) {
            this.cellulars.push(item);
          }
        });
      }
      this.formQuery = { ...this.formQuery, cellularCode: null };
    },
    // 获取调价审核任务数量
    async getAuditTaskBoard() {
      try {
        this.auditTaskBoard = (await loadAuditTaskBoard()) || {};
      } catch (e) {
        message('错误', '获取调价审核任务数量失败', 'error');
      }
    },
  },
  async mounted() {
    // 获取调价审核任务数量
    this.getAuditTaskBoard();
  },
};
